package com.googlewell.zelix.test;

import me.coley.recaf.control.Controller;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.util.struct.ListeningMap;
import me.coley.recaf.workspace.ClassResource;
import me.coley.recaf.workspace.Workspace;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class WriteClass {


    public static void test1(Controller controller, String className) {
        //dump类

        //类加载到工作空间
        String path = "c:\\dump\\";
        ClassResource resource = null;
        try {
            resource = new ClassResource(Paths.get(path +  "com.googlewell.zelix.test.WriteClass.class"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        controller.setWorkspace(new Workspace(resource));


        //打开类视图
        GuiController gController = (GuiController) controller;
        gController.windows().getMainWindow().openClass(resource, "com/googlewell/zelix/test/WriteClass");
    }

    public static void test(Controller controller, String className) {

        //类加载到工作空间
        String path = "c:\\dump\\";
        ClassResource resource = null;
        try {
            resource = new ClassResource(Paths.get(path +  "com.googlewell.zelix.test.WriteClass.class"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        controller.setWorkspace(new Workspace(resource));


        GuiController gController = (GuiController) controller;
        gController.windows().getMainWindow().openClass(resource, "com/googlewell/zelix/test/WriteClass");

        ListeningMap<String, byte[]> classes = controller.getWorkspace().getPrimary().getClasses();

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }else{
            return;
        }
        byte[] rawClass = classes.get(className);
        try {
            Files.write(Paths.get(path + className.replaceAll("/", ".") + ".class"), rawClass, new OpenOption[]{StandardOpenOption.CREATE});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
